package com.gzk.basic.interceptor;

import com.gzk.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //拿token

        String token = request.getHeader("token");
        //判断
        if(!StringUtils.isEmpty(token)){
            //在redis里面取值
            Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);
            //判断
            if(logininfo != null){
                //登录没过期，刷新时间，直接放行
                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
                return true;
            }
        }

        //logininfo为空或者token为空，直接跳转到登录页
        response.setContentType("application/json,charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        //返回 {"success":false,"message":"noLogin"}
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        //不放行
        return false;

    }
}
